package com.cirnoworks.guice;

import java.util.ArrayList;

import javax.inject.Singleton;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class LifeCycleService {
	private Logger LOG = LoggerFactory.getLogger(LifeCycleService.class);
	private ArrayList<LifeCycle> registions = new ArrayList<LifeCycle>();
	private boolean dead = false;

	public synchronized void register(LifeCycle lifeCycle) {
		if (dead) {
			throw new RuntimeException("LifeCycle is currently dead.");
		} else {
			registions.add(lifeCycle);
		}
	}

	public synchronized void shutdown() {
		dead = true;
		for (LifeCycle lifeCycle : registions) {
			try {
				lifeCycle.shutdown();
			} catch (Throwable t) {
				LOG.error("Error shutting down " + lifeCycle);
			}
		}
		registions = null;
	}
}
